#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <cstring>
#include <strings.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <memory>

enum error
{
    SOCK_ERROR = 2,
    BIND_ERROR,
    RECVFROM_ERROR
};

static const std::string Or_ip = "127.0.0.1";

class udp_serve
{
    typedef std::function<void(std::string, int&, sockaddr_in&)> func_t;
public:
    udp_serve(func_t handle_fun, const uint16_t &port, const std::string &ip = Or_ip)
        : _sockfd(-1), _port(port), _ip(ip), _handle_fun(handle_fun) {}

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            std::cerr << "socket:" << errno << ":" << strerror(errno) << std::endl;
            exit(SOCK_ERROR);
        }
        struct sockaddr_in local;
        bzero(&local, sizeof(sockaddr_in));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int ret = bind(_sockfd, (sockaddr *)&local, sizeof(sockaddr_in));
        if (ret == -1)
        {
            std::cerr << "bind:" << errno << ":" << strerror(errno) << std::endl;
            exit(BIND_ERROR);
        }
    }

    void start()
    {
        while (1)
        {
            char buffer[256];
            sockaddr_in client;
            u_int32_t sockaddr_in_size = sizeof(sockaddr_in);
            int size = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (sockaddr *)&client, &sockaddr_in_size);
            if (size == -1)
            {
                std::cerr << "recvfrom:" << errno << ":" << strerror(errno) << std::endl;
                exit(RECVFROM_ERROR);
            }
            std::string client_ip = inet_ntoa(client.sin_addr);
            buffer[size] = 0;
            _handle_fun(buffer, _sockfd, client);
        }
    }

    ~udp_serve() {}

private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
    func_t _handle_fun;
};